import fs from "fs-extra"
import path from "node:path"
import { fileURLToPath } from "node:url";

export default function router(match) {
  let time = new Date().getTime()
  const dayTime = 1000 * 60 * 60 * 24
  const ips = []
  const __dirname = path.dirname(fileURLToPath(import.meta.url))

  return async function (ctx, next) {
    let reqPath = ctx.request.path
    let ip = ctx.ip

    if (match.test(reqPath)) {
      // 1 获取当前时间
      const now = new Date().getTime()
      // 2 读取 data 数据
      const data = fs.readJSONSync(path.resolve(__dirname, "./data.json"))
      // 3 判断过了一天
      if (time + dayTime < now) {
        console.log("清空ips：", ips);
        time += dayTime
        ips.length = 0
        data.today = 0
      }
      // 4 储存 ip
      if (!ips.includes(ip)) {
        ips.push(ip)
        data.total += 1
        data.today += 1
        fs.writeJSONSync(path.resolve(__dirname, "./data.json"), data)
      }
      // 5 根据路径响应接口
      if (reqPath === "/api/message") {
        ctx.status = 200
        ctx.body = data
      }
    }
    await next()
  }
}
